//
//  OAuthViewController.swift
//  SinaWeibo--swift
//
//  Created by 蒋春萌 on 15/10/7.
//  Copyright © 2015年 蒋春萌. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    //将根视图强转为一个webView 强转过程中根视图控制器不是webView就直接挂啦
    //readOnly 简写
    var webView:UIWebView{
        get{
            return view as! UIWebView
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
//    加载授权网页
    func loadOAuthPage(){
        
        webView.loadRequest(NSURLRequest(URL: NetWorkTool.sharedTools.loadOauthPage()))
        
    }
    
//   关闭按钮的点击事件
    @IBAction func close(sender: AnyObject) {
//        消除该控制器
        dismissViewControllerAnimated(true, completion: nil)
        
        SVProgressHUD.dismiss()
    }
//    自动填充按钮的点击事件
    @IBAction func defaultAccount(sender: AnyObject) {
        let jsString = "document.getElementById('userId').value='15562589692';document.getElementById('passwd').value='jcm5230269'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
//    请求用户token
    func loadAccountToken(code:String){
    
        NetWorkTool.sharedTools.loadAccountToken(code)
    }
    
//    实现webView的代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        将请求的网址转化为字符串
        let urlString = request.URL!.absoluteString
//        print(urlString)
        //https://api.weibo.com/oauth2/authorize?client_id=718658370&redirect_uri=http://www.baidu.com
        //https://api.weibo.com/oauth2/authorize
        //http://www.baidu.com/?code=1fc4d1aeeb0e2f2c5412c95776311583
        //http://weibo.cn/dpool/ttt/h5/reg.php?wm
        if urlString.hasPrefix("https://api.weibo.com/"){
            return true
        }
        if !urlString.hasPrefix(NetWorkTool.sharedTools.WB_redirect_uri){
            return false
        }
        //拿到请求授权的code码
        //request.URL?.query 拿到url请求的参数=值
        if let query = request.URL?.query {
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code)
//            请求token
            loadAccountToken(code)
            
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {

//        将导航栏的title设置为应用名称
        let jsString = "document.title"
        title = webView.stringByEvaluatingJavaScriptFromString(jsString)
        SVProgressHUD.dismiss()
    }
}
